package com.lmt.service.impl;

import com.lmt.base.BaseService;
import com.lmt.base.ResultData;
import com.lmt.entity.DigitalDictionary;
import com.lmt.entity.search.DigitalDictionarySearch;
import com.lmt.repository.DigitalDictionaryRepository;
import com.lmt.service.DigitalDictionaryService;
import com.lmt.util.RedisCacheUtil;
import com.lmt.util.ResultUtil;
import com.lmt.util.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@Service("DigitalDictionaryServiceImpl")
public class DigitalDictionaryServiceImpl extends BaseService implements DigitalDictionaryService {

	private final DigitalDictionaryRepository digitalDictionaryRepository;

	private final RedisCacheUtil redisCacheUtil;

	@Autowired
	public DigitalDictionaryServiceImpl(DigitalDictionaryRepository digitalDictionaryRepository,
										RedisCacheUtil redisCacheUtil) {
		this.digitalDictionaryRepository = digitalDictionaryRepository;
		this.redisCacheUtil = redisCacheUtil;
	}

	@Override
	public ResultData save(DigitalDictionary digitalDictionary) {
		if (null != this.digitalDictionaryRepository.findByCode(digitalDictionary.getCode())) {
			return ResultUtil.newFail("该编码已经存在：" + digitalDictionary.getCode());
		}
		digitalDictionary.setCreator(redisCacheUtil.getUserName(digitalDictionary));
		this.digitalDictionaryRepository.save(digitalDictionary);
		if (null != digitalDictionary.getId()) {
			return ResultUtil.newSuccess("添加数据字典成功");
		}
		return ResultUtil.newFail("添加数据字典失败");
	}

	@Override
	public ResultData findAll(DigitalDictionarySearch digitalDictionarySearch) {
		int currentPage = digitalDictionarySearch.getCurrentPage() - 1;
		int pageSize = digitalDictionarySearch.getPageSize();
		Order codeOrder = new Order(Sort.Direction.ASC, "code");
		List<Order> orders = new ArrayList<>();
		orders.add(codeOrder);
		PageRequest pageRequest = PageRequest.of(currentPage, pageSize, Sort.by(orders));
		Page<DigitalDictionary> page = this.digitalDictionaryRepository.findAll(pageRequest);
		return ResultUtil.newSuccess("查询成功", page);
	}

	@Override
	public ResultData findOneById(String id) {
		Optional<DigitalDictionary> result = this.digitalDictionaryRepository.findById(id);
		if (!result.isPresent()) {
			return ResultUtil.newFail("该数据字典不存在");
		} else {
			return ResultUtil.newSuccess("成功获取数据字典", result);
		}
	}

	@Override
	public ResultData update(DigitalDictionary digitalDictionary) {
		Optional<DigitalDictionary> old = this.digitalDictionaryRepository.findById(digitalDictionary.getId());
		if (!old.isPresent()) {
			return ResultUtil.newFail("修改的数据字典不存在");
		}
		this.digitalDictionaryRepository.save(digitalDictionary);
		return ResultUtil.newSuccess("修改数据字典成功");
	}

	@Override
	public ResultData search(DigitalDictionarySearch digitalDictionarySearch) {
		String keyword = digitalDictionarySearch.getKeyword();
		int currentPage = digitalDictionarySearch.getCurrentPage() - 1;
		int pageSize = digitalDictionarySearch.getPageSize();
		Order codeOrder = new Order(Sort.Direction.ASC, "code");
		List<Order> orders = new ArrayList<>();
		orders.add(codeOrder);
		PageRequest pageRequest = PageRequest.of(currentPage, pageSize, Sort.by(orders));
		if (!StringUtils.isEmpty(keyword)) {
			Page result = this.digitalDictionaryRepository
					.findByCodeLikeOrDescriptionLikeOrDesignationLikeOrCreatorLike(keyword, keyword, keyword, keyword,
							pageRequest);
			return ResultUtil.newSuccess("查询成功", result);
		}
		return this.findAll(digitalDictionarySearch);
	}

	@Override
	public ResultData delete(List<DigitalDictionary> digitalDictionaries) {
		for (DigitalDictionary digitalDictionary : digitalDictionaries) {
			this.digitalDictionaryRepository.deleteById(digitalDictionary.getId());
		}
		return ResultUtil.newSuccess("删除数据字典成功");
	}

	@Override
	public ResultData getParentCodeTree() {
		List<Map<String, Object>> result = this.getTreeOptions();
		return ResultUtil.newSuccess("成功获取父节点选择树", result);
	}

	@Override
	public ResultData getChildrenForSelect(String parentCode) {
		List<DigitalDictionary> options = this.digitalDictionaryRepository.findByParentCode(parentCode);
		return ResultUtil.newSuccess("成功获取选项", options);
	}

	private List<Map<String, Object>> getTreeOptions() {
		List<Map<String, Object>> result = new ArrayList<>();
		List<DigitalDictionary> firstLevel = new ArrayList<>();
		List<DigitalDictionary> children = new ArrayList<>();
		List<DigitalDictionary> all = this.digitalDictionaryRepository.findAll();
		Map<String, Map<String, Object>> temp = new HashMap<>(all.size());
		for (DigitalDictionary classify : all) {
			Map<String, Object> tempOption = new HashMap<>(3);
			tempOption.put(SystemConstant.PROPS_CODE, classify.getCode());
			tempOption.put(SystemConstant.PROPS_LABEL, classify.getDesignation());
			tempOption.put(SystemConstant.PROPS_CHILDREN, new ArrayList<>());
			temp.put(classify.getCode(), tempOption);
			if (null == classify.getParentCode()) {
				firstLevel.add(classify);
			} else {
				children.add(classify);
			}
		}
		for (DigitalDictionary child : children) {
			//noinspection unchecked
			((List) temp.get(child.getParentCode()).get(SystemConstant.PROPS_CHILDREN)).add(temp.get(child.getCode()));
		}
		for (DigitalDictionary classify : firstLevel) {
			result.add(temp.get(classify.getCode()));
		}
		return result;
	}
}
